package ct.view;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FenetreImportObligation extends JFrame implements ActionListener {
	private static final long serialVersionUID = 1L;
	private JTextField importurlfield;
	private PanelPortefeuille portef;

	public FenetreImportObligation(PanelPortefeuille portef) {
		super("Import depuis l'Internet");
		this.portef = portef;
		this.setSize(400, 60);
		this.setLocationRelativeTo(null);
		this.setAlwaysOnTop(true);

		JButton Bimport = new JButton("Importer");
		Bimport.addActionListener(this);

		JPanel boutonpanel = new JPanel(new GridLayout(1, 1));
		boutonpanel.add(Bimport);

		importurlfield = new JTextField();
		JPanel textfield = new JPanel(new GridLayout(1, 1));
		textfield.add(importurlfield);

		JPanel content = new JPanel(new BorderLayout());
		content.add(importurlfield, BorderLayout.CENTER);
		content.add(Bimport, BorderLayout.EAST);

		this.setContentPane(content);
	}

	public void actionPerformed(ActionEvent e) {
		if (importurlfield.getText().indexOf("http://") == 0) {
			try {
				this.portef.getPortefeuille().clear();
				this.portef.getPortefeuille().importCSVFile(
						importurlfield.getText());
			} catch (IOException ioe) {
				JOptionPane.showMessageDialog(this, "Impossible de lire l'URL",
						"Erreur IO", JOptionPane.ERROR_MESSAGE);
			} catch (ParseException pe) {
				JOptionPane.showMessageDialog(this,
						"Format de fichier inconnu", "Erreur Format",
						JOptionPane.ERROR_MESSAGE);
			}

			this.portef.MAJ();
			this.dispose();
		} else {
			importurlfield.setText("URL Invalide...");
		}

	}

}
